package com.sghd.charge.controller;

import com.sghd.charge.module.model.ChannelType;
import com.sghd.charge.module.model.ChargeCode;
import com.sghd.charge.module.model.OrderInfo;
import com.sghd.charge.module.payment.ChannelProcessor;
import com.sghd.charge.module.utils.IpUtil;
import com.sghd.common.utils.json.JsonUtils;
import com.sghd.common.utils.model.Result;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

@RestController
public class ChargeController extends AbstractController {

    @RequestMapping(value = "/charge/{channelType}", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<OrderInfo> charge(@PathVariable("channelType") ChannelType channelType, @RequestParam("serverId") int serverId,
                                    @RequestParam("playerId") long playerId, @RequestParam("goodsId") String goodsId,
                                    @RequestParam("sign") String sign, HttpServletRequest request) {
        String ip = IpUtil.getIpAddr(request);
        try {
            boolean valid = chkSign("SPG", sign, serverId, playerId, goodsId);
            if (!valid) {
                return Result.ERROR(ChargeCode.SIGN_ERROR.getValue());
            }
            ChannelProcessor processor = getProcessor(channelType);
            if (processor == null) {
                return Result.ERROR(ChargeCode.CHANNEL_TYPE_ERROR.getValue());
            }
            OrderInfo info = processor.generateOrder(playerId, serverId, goodsId, ip);
            Result<OrderInfo> result = Result.SUCCESS(info);
            System.out.println(JsonUtils.object2String(result));
            return result;
        } catch (Exception e) {
            logger.error("来自[{}]渠道，[{}]游戏服的玩家[{}]充值[{}]出现未知错误", channelType, serverId, playerId, goodsId, e);
            return Result.ERROR(ChargeCode.UNKNOWN_ERROR.getValue());
        }
    }


    @RequestMapping(value = "/notify/{channelType}", method = {RequestMethod.GET, RequestMethod.POST})
    public String notify(@PathVariable ChannelType channelType, ServletRequest request) {
        try {
            ChannelProcessor processor = getProcessor(channelType);
            if (processor == null) {
                return String.valueOf(ChargeCode.CHANNEL_TYPE_ERROR.getValue());
            }
            return processor.notify(request);
        } catch (Exception e) {
            logger.error("[{}]平台充值验证出现未知错误", channelType, e);
            return String.valueOf(ChargeCode.UNKNOWN_ERROR.getValue());
        }
    }
}
